#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "UnitTest.h"

///////////////////////////////////////////////////////////
//
//CUnitTest implementation
//
///////////////////////////////////////////////////////////
CUnitTest::CUnitTest()
{
   m_caseList = m_tail = NULL;
   m_caseCount = 0;
}

CUnitTest::~CUnitTest()
{
   TestCaseNode* cur = m_caseList;
   TestCaseNode* next;
   while (cur) {
      assert (cur);
      next = cur->next;
      delete cur;
      cur = next;
   }
}

int CUnitTest::AddCase(const char* name, CTestGroup* test)
{
   TestCaseNode* cur = m_caseList;
   assert(test);
   assert(name);
   // check whether this is duplicated testcase name.

   while (cur) {
      assert(cur);
      if (strcmp(cur->CaseName, name) == 0) {
         printf ("@@@!!!@@@ ERROR! duplicated testcase name: %s\n"
                 "TESTING ABORTED!\n",
                 name);
         exit(1);
      }
      cur = cur->next;
   }
   TestCaseNode* tc = new TestCaseNode;
   tc->CaseName = name;
   tc->Testcase = test;
   tc->next = NULL;
   
   if (m_tail) {
      m_tail->next = tc;
   } else {
      m_caseList = tc;
   }
   
   m_tail = tc;
   m_caseCount++;
      
   return m_caseCount;
}

int CUnitTest::RunAll()
{
   TestCaseNode* cur = m_caseList;
   int passed = 0;
   int failed = 0;

   while (cur) {
      assert(cur);
      printf ("-------------------------------\n");
      printf ("%s\n", cur->CaseName);
      m_pass = true;
      cur->Testcase->Setup();
      cur->Testcase->TestFunc() ;
      cur->Testcase->TearDown();
      if (m_pass) {
         printf ("pass\n");
         passed++;
      } else {
         printf ("FAIL\n");
         failed++;
      }
      cur = cur->next;
   }

   printf ("==================================\n");
   printf ("%d test case(s) executed. %d passed and %d failed.\n", passed+failed, passed, failed);
   return 0;
}

